package com.cqcet.wenchuang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqcet.wenchuang.common.customException.CustomException;
import com.cqcet.wenchuang.dto.CategoryDto;
import com.cqcet.wenchuang.entity.Category;
import com.cqcet.wenchuang.entity.Goods;
import com.cqcet.wenchuang.mapper.CategoryMapper;
import com.cqcet.wenchuang.service.CategoryService;
import com.cqcet.wenchuang.service.GoodsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CateGoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private GoodsService goodsService;

    /**
     * 获取当前分类下的所有商品
     *
     * @param id
     * @return
     */
    @Override
    public CategoryDto getByIdWithGoods(Long id) {
        //查询分类信息
        Category category = this.getById(id);

        //拷贝category对象的属性拷贝至categoryDto对象
        CategoryDto categoryDto = new CategoryDto();
        BeanUtils.copyProperties(category, categoryDto);

        //根据分类id查询商品
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Goods::getCategoryId, id);

        //设置排序条件，根据更新时间降序排
        queryWrapper.orderByDesc(Goods::getUpdateTime);

        //执行查询
        List<Goods> goodsList = goodsService.list(queryWrapper);

        //将商品list集合存放入信息交换对象
        categoryDto.setGoodsList(goodsList);

        return categoryDto;
    }

    /**
     * 根据id删除前判断该分类是否为空，不为空则不能删除
     *
     * @param id
     */
    @Override
    public void remove(Long id) {
        CategoryDto categoryDto = this.getByIdWithGoods(id);
        if (categoryDto.getGoodsList().size() > 0) {
            throw new CustomException("该分类下有商品,无法删除");
        }
        this.removeById(id);
    }
}
